/* eslint-disable no-unused-vars */
import React, { useEffect, useState } from "react";
import styles from './launch.module.css'
import icon_switch_off from "@/assets/icon_switch_off.webp";
import icon_switch_on from "@/assets/icon_switch_on.webp";
import icon_add from "@/assets/icon_add.webp";
import { Toast } from "antd-mobile";
import { resultService } from "@/store/actions/ResultService";


export default function ConfigLayout() {

    const [configList, setConfigList] = useState([
        {
            label: "加纳",
            country: "ghana",
            categorys: [
                {
                    label: "总榜",
                    value: "main",
                    checked: false
                },
                {
                    label: "金融",
                    value: "finance",
                    checked: false
                }
            ],
            account: {
                email: "",
                password: ""
            },
            checked: false
        },
        {
            label: "科特",
            country: "cote",
            categorys: [
                {
                    label: "总榜",
                    value: "main",
                    checked: false
                },
                {
                    label: "金融",
                    value: "finance",
                    checked: false
                }
            ],
            account: {
                email: "",
                password: ""
            },
            checked: false
        },
        {
            label: "喀唛隆",
            country: "cameroon",
            categorys: [
                {
                    label: "总榜",
                    value: "main",
                    checked: false
                },
                {
                    label: "金融",
                    value: "finance",
                    checked: false
                }
            ],
            account: {
                email: "",
                password: ""
            },
            checked: false
        }
    ]);

    useEffect(() => {

        return () => {
        }
    }, [])

    const onHandleCountryClick = (country) => {
        const newState = configList.map(item => {
            if (item.country === country) {
                const newChecked = !item.checked;
                return {
                    ...item,
                    checked: newChecked,
                    categorys: item.categorys.map(c => ({ ...c, checked: newChecked }))
                };
            }
            return item;
        });

        setConfigList(newState);
    };


    const onHandlerTypeClick = (country, label) => {
        const newState = configList.map(item => {
            if (item.country === country) {
                const updatedCategorys = item.categorys.map(category =>
                    category.label === label
                        ? { ...category, checked: !category.checked }
                        : category
                );

                const anyChecked = updatedCategorys.some(c => c.checked);

                return {
                    ...item,
                    categorys: updatedCategorys,
                    checked: anyChecked
                };
            }
            return item;
        });

        setConfigList(newState);
    };

    const onHandleEmailInputBlur = (e, country) => {

    }

    const onHandleEmailInputChange = (e, country) => {
        let input = e.target.value || "";
        const newState = configList.map(item => {
            if (item.country === country) {
                return {
                    ...item,
                    account: {
                        ...item.account,
                        email: input
                    }
                };
            }
            return item;
        });
        setConfigList(newState);
    }

    const onHandlePasswordInputBlur = (e, country) => {

    }

    const onHandlePasswordInputChange = (e, country) => {
        let input = e.target.value || "";
        const newState = configList.map(item => {
            if (item.country === country) {
                return {
                    ...item,
                    account: {
                        ...item.account,
                        password: input
                    }
                };
            }
            return item;
        });
        setConfigList(newState);
    }

    const onHandleStartClick = () => {
        // list = [{country:ghana, categorys:[ghana, cote, cameroon], account:{email, password}}]
        const params = configList
            .filter(item => item.checked && item.account.email.indexOf("@") !== -1 && item.account.password.length > 0)
            .map(({ country, categorys, account }) => ({
                country,
                account,
                categorys: categorys
                    .filter(cate => cate.checked)
                    .map(cate => cate.value)
            }))
            .filter(param => param.categorys.length > 0); // 可选：过滤掉空分类

        if (params.length === 0) {
            Toast.show("请选择爬取地区与类型/输入有效的账号密码");
            return;
        }

        // 启动任务
        reqFetching(params);
    }

    const reqFetching = async (params) => {
        try {
            const { success, data } = await resultService.startScraping(params);
            if (success) {
                Toast.show("任务启动成功, 预计需要1.5小时");
            }
        } catch (error) {
            console.error("登录处理出错:", error);
        }
    }

    return (
        <div className={styles.launchListContent}>

            {configList && configList.length > 0 && configList.map((value, index) => {
                return <div className={`${styles.launchColContent}`} key={index}>
                    <div className={styles.launchRowContent} onClick={() => { onHandleCountryClick(value.country) }}>
                        <img className={styles.launchCheckbox} src={value.checked ? icon_switch_on : icon_switch_off} alt="" />
                        <div className={styles.launchTitle}>{value.label}</div>
                    </div>

                    <div className={`${styles.launchRowContent} ${styles.launchTopMargin24}`}>
                        <div className={`${styles.launchSubTitle} ${styles.launchRightMargin16}`}>分类:</div>
                        {value.categorys && value.categorys.length > 0 && value.categorys.map((cateValue, cateIndex) => {
                            return <div key={cateIndex} className={`${styles.launchRowContent} ${styles.launchRightMargin16}`} onClick={() => { onHandlerTypeClick(value.country, cateValue.label) }}>
                                <img className={styles.launchCheckbox} src={cateValue.checked ? icon_switch_on : icon_switch_off} alt="" />
                                <div className={styles.launchSubTitle}>{cateValue.label}</div>
                            </div>
                        })}
                    </div>

                    <div className={`${styles.launchRowContent} ${styles.launchTopMargin24}`}>
                        <div className={`${styles.launchSubTitle} ${styles.launchRightMargin16}`}>账号:</div>
                        <input className={styles.launchInputContent}
                            placeholder="输入邮箱"
                            type="text"
                            value={value.account.email}
                            onBlur={(e) => { onHandleEmailInputBlur(e, value.country) }}
                            onChange={(e) => { onHandleEmailInputChange(e, value.country) }}
                            autoComplete="off" />
                    </div>

                    <div className={`${styles.launchRowContent} ${styles.launchTopMargin24}`}>
                        <div className={`${styles.launchSubTitle} ${styles.launchRightMargin16}`}>密码:</div>
                        <input className={styles.launchInputContent}
                            placeholder="输入密码"
                            type="text"
                            value={value.account.password}
                            onBlur={(e) => { onHandlePasswordInputBlur(e, value.country) }}
                            onChange={(e) => { onHandlePasswordInputChange(e, value.country) }}
                            autoComplete="off" />
                    </div>

                    <div className={`${styles.launchSectionLine} ${styles.launchTopMargin24} ${styles.launchBottomMargin24}`}></div>
                </div>
            })}

            <div className={styles.launchFetchButton} onClick={onHandleStartClick}>
                <img className={styles.launchCheckbox} src={icon_add} alt="" />
                新增爬取
            </div>
        </div>
    )
}